import { stringify } from 'querystring';
import { history } from 'umi';
import { fakeAccountLogin, logout } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

const Model = {
  namespace: 'login',
  state: {
    // status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      // 发送请求，执行登录
      const response = yield call(fakeAccountLogin, payload);
      // 如果登录成功
      if(response.status === undefined) {
        message.success('登录成功!')
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        })
        // 跳转到首页
        history.replace('/')
      }
    },

    // 退出登录
    *logout(_, { call }) {
      const hide = message.loading('退出中...')
      // 调用接口，退出登录
      const response = yield call(logout)
      // 判断是否请求成功
      if(response.status === undefined) {
        hide()
        // 清除localStorage 中的 token 和 userInfo
        localStorage.removeItem('access_token')
        localStorage.removeItem('userInfo')
        message.success('退出登录成功!')
        // 重定向
        history.replace('/login')
      }
      hide()
    }

  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      // return { ...state, status: payload.status, type: payload.type };
      // 将token存入localStorage
      localStorage.setItem('access_token', payload.access_token)
      return { ...state }
    },
  },
};
export default Model;
